﻿using B.S.GridManage.Api.Write.DTOs;
using B.S.GridManage.ErrorCode;
using Consul;
using System.Net.Http.Json;

namespace B.S.GridManage.Api.Write.PhsicalGridService
{
    public class PhsicalGridDiscovery
    {
        private readonly HttpClient httpClient;
        private readonly IConsulClient consulClient;

        public PhsicalGridDiscovery(IHttpClientFactory factory,IConsulClient consulClient)

        {
            this.httpClient = factory.CreateClient();
            this.consulClient = consulClient;
        }

        //根据服务名查找实例的ip+端口
        public async Task<string>  GetUrlAsync(string serviceName) {
            var service = await consulClient.Health.Service(serviceName);
            var length = service.Response.Length;
            var index = new Random().Next(0, length - 1);
            var instance = service.Response[index];

            return $"http://{instance.Service.Address}:{instance.Service.Port}";
        }
        //根据接口url 调用接口,获取数据
        public async Task<ApiResult<List<PhysicalGridDto>>> SearchPhysicalAsync(string url) {
            var res = await httpClient.GetAsync(url);
            res.EnsureSuccessStatusCode();
            return await res.Content.ReadFromJsonAsync<ApiResult<List<PhysicalGridDto>>>();
        }
    }
}
